<template>
  <!-- 老规矩一个模块下面只能包含着一个div -->
  <div>
    <!-- 第一排 -->
    <el-row :gutter="30">
      <el-col :span="20">
        菜品状态:
        <el-select v-model="status" clearable placeholder="菜品状态">
          <el-option
              v-for="item in options2"
              placeholder='请选择'
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        菜品类型:
        <el-select v-model="value" clearable placeholder="菜品类型">
          <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.typeName"
              :value="item.id">
          </el-option>
        </el-select>
        菜品名字:
        <el-input v-model="input" placeholder="请输入菜品名称" style="width:300px;"></el-input>
        <el-button type="primary" @click="queryFood()">菜品查询</el-button>
        <el-button type="primary" @click="tianjiaTanChuang()">菜品上新</el-button>
        <el-button type="primary" @click="dialogVisible = true">菜品类型</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="30">
      <el-col :span="24" style="margin:20px 0px 0px 100px;align:center;">
        <!-- 表格展示数据 -->
        <el-table :data="foodData" border style="width:1100px;">
          <el-table-column fixed prop="id" label="序号" width="100" align="center">
          </el-table-column>
          <el-table-column prop="foodName" label="食物名称" width="120" align="center">
          </el-table-column>
          <el-table-column prop="foodType" label="食物类型" width="120" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.foodType == 1">荤菜</span>
              <span v-if="scope.row.foodType == 2">素菜</span>
              <span v-if="scope.row.foodType == 3">主食</span>
              <span v-if="scope.row.foodType == 4">饮品</span>
              <span v-if="scope.row.foodType == 5">清真类</span>
              <span v-if="scope.row.foodType == 6">小吃</span>
            </template>
          </el-table-column>

          <el-table-column prop="foodImg" label="食物图片" width="180" align="center">
            <template slot-scope="scope">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.foodImg"
                  :preview-src-list="[scope.row.foodImg]"
                  fit="contain">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="foodPrice" label="食物价格" width="120" align="center">
          </el-table-column>
          <el-table-column prop="foodInventory" label="食物剩余数量" width="120" align="center">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="300px" >
            <template slot-scope="scope">
              <!-- 这块下面是修改按钮 -->
              <el-button type="primary" @click="updateFoodById(scope.row)">修改
              </el-button>
              <!-- 这块下面是上架按钮 -->
              <el-button type="info" v-if="scope.row.foodStatus == 0" @click="shangFoodStatus(scope.row.id)">未售
              </el-button>
              <!-- 这块下面是下架按钮 -->
              <el-button type="success" v-if="scope.row.foodStatus == 1" @click="xiaFoodStatus(scope.row.id)">在售
              </el-button>
              <!-- 这块下面是删除按钮 -->
              <el-button type="danger" @click="deleteFoodById(scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!--下面都是弹出层-->
    <div>
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" center width="37%">
        <el-form :model="form">
          <el-form-item label="食物名称" :label-width="formLabelWidth">
            <!--autocomplete="off" 禁止自动补全  -->
            <el-col :span="18">
              <el-input v-model="form.foodName" autocomplete="off"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="食物类型" :label-width="formLabelWidth">
            <el-col :span="18">
              <el-select v-model="form.foodType" clearable placeholder="菜品类型">
                <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.typeName"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="食物图片" :label-width="formLabelWidth">
            <el-upload
                name="foodFile"
                class="avatar-uploader"
                action="http://localhost:9527/food/upload"
                :show-file-list="false"
                :on-success="fileUploadSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.foodImg" :src="form.foodImg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth">
            <el-col :span="18">
              <el-input v-model="form.foodPrice" autocomplete="off"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="库存" :label-width="formLabelWidth">
            <el-col :span="18">
              <el-input v-model="form.foodInventory" autocomplete="off"></el-input>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveFood">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--菜品类型的弹出框-->
    <el-dialog
        title="菜品类型"
        :visible.sync="dialogVisible"
        width="40%"
        >
      <span>
        <!--把值绑定为false意思是可以删除-->
        <el-tag
            :key="tag.name"
            v-for="tag in this.options"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
            @click="changeValue(tag)">
            {{tag.typeName}}
        </el-tag>
        <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">新增菜品类型</el-button>
      </span>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Canpin",
  data() {
    return {
      dialogTitle: '',//弹出框标题
      dialogFormVisible: false,//弹出层开关 默认设置为不弹出
      dialogVisible:false,//菜品类型 弹出层开关 默认设置为不弹出
      // 定义表单对象
      //给表单项初始值
      form: {
        id: 0,
        foodName: '',
        foodType: '',
        foodImg: '',
        foodPrice: '',
        foodInventory: '',
      },
      input: '',//搜索框
      options: [],
      value: '',//类型下拉框
      options2: [{
        value: '1',
        label: '可以购买'
      }, {
        value: '0',
        label: '无法购买'
      }],
      status: '',//菜品状态选择框
      foodData: [],//所有菜品信息
      formLabelWidth: '120px',//宽度
      dynamicTags: [], //保存tag标签，此处用来保存菜品类型
      inputVisible: false,
      inputValue: '' //新增的那个文本框
    }
  },
  //钩子函数
  mounted() {
    this.getAllFood(); //全查菜品
    this.getFoodType();//全查菜品类型
  },
  methods: {
    // 全查方法
    getAllFood() {
      //请求方式为get
      this.$axios.get("http://localhost:9527/backstagesupporter/food/getAllFood").then(res => {//获取返回结果
        this.foodData = res.data.data;
        console.log(res)
      }).catch(e =>{
        console.log(e)
      })
    },
    // 查询菜品类型
    getFoodType() {
      //请求方式为get
      this.$axios.get("http://localhost:9527/backstagesupporter/getFoodType").then(res => {//获取返回结果
        this.options = res.data.data;
        console.log(this.options)

      }).catch(e =>{
        console.log(e)
      })
    },
    //模糊查和类型查
    queryFood() {
      //请求方式为get
      this.$axios.get("http://localhost:9527/backstagesupporter/food/getAllFood",
          {
            params: {
              foodName: this.input,
              foodType: this.value,
              foodStatus: this.status
            }
          }).then(res => {//获取返回结果
        this.foodData = res.data.data;
      })
    },
    //保存菜品方法(添加和修改都是这个方法)
    saveFood() {
      //如果有id值,那就进修改
      if (this.form.id != null) {
        // alert("进的修改")
        //请求方式为post
        this.$axios.post("http://localhost:9527/backstagesupporter/food/updateFood",
            {
              id: this.form.id,
              foodName: this.form.foodName,
              foodType: this.form.foodType,
              foodImg: this.form.foodImg,
              foodPrice: this.form.foodPrice,
              foodInventory: this.form.foodInventory
            }).then(res => {//获取返回结果
          this.updateSuccess()//修改成功的通知方法
          this.dialogFormVisible = false//关闭弹窗
          this.form = {}//清空表单
          this.foodData = res.data.data;//更新数据
        })
      } else {//如果没有id值那就进的添加
        // alert("进的添加")
        //请求方式为post
        this.$axios.post("http://localhost:9527/backstagesupporter/food/saveFood",
            {
              foodName: this.form.foodName,
              foodType: this.form.foodType,
              foodImg: this.form.foodImg,
              foodPrice: this.form.foodPrice,
              foodInventory: this.form.foodInventory
            }).then(res => {//获取返回结果
          this.saveSuccess()//添加成功的通知方法
          this.dialogFormVisible = false//关闭弹窗
          this.form = {}//清空表单
          this.foodData = res.data.data;//更新数据
        })
      }
    },
    //添加菜品的弹窗,为了清除form的值,所以又设置了一下这里
    tianjiaTanChuang() {
      this.form = {} //清空form的值
      this.dialogFormVisible = true //将弹出层设置为弹出
      this.dialogTitle = '添加菜品' //修改弹出层标题
    },
    //删除食物的模块
    deleteFoodById(id) {
      //消息选择框
      this.$confirm('此操作将永久删除菜品, 是否继续?', '警 告 ! ! !', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        //调用接口传入id删除数据
        //请求方式是delete
        this.$axios.delete("http://localhost:9527/backstagesupporter/food/deleteFoodById", {
          params: {//发送请求
            id: id
          }
        }).then(res => {//获取返回结果
          // 弹出删除成功消息
          this.deleteSuccess();
          this.dialogFormVisible = false//关闭弹窗
          // 重新赋值（后台返回值重新调用了全查）
          this.foodData = res.data.data;
        }).catch()
      })
    },
    //修改食物的模块
    updateFoodById(row) {
      this.form = row //将这一行的值赋给弹出层
      this.dialogFormVisible = true //将弹出层设置为弹出
      this.dialogTitle = '修改菜品信息' //修改弹出层标题
    },
    //上架食物
    shangFoodStatus(id) {
      //消息选择框
      this.$confirm('是否将菜品上架?', '您好', {
        confirmButtonText: '上架',
        cancelButtonText: '取消',
      }).then(() => {
        //修改食物状态
        this.$axios.post("http://localhost:9527/backstagesupporter/food/updateFoodStatus",
            {
                id: id,
              foodStatus: 1
            }).then(res => {//获取返回结果
          this.updateStatus1Success()//上架成功的通知方法
          this.foodData = res.data.data;//更新数据
        })
      })
    },
    //下架食物
    xiaFoodStatus(id) {
      //消息选择框
      this.$confirm('您确定要将菜品下架吗?', '警 告 ! ! !', {
        confirmButtonText: '下架',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        //修改食物状态
        this.$axios.post("http://localhost:9527/backstagesupporter/food/updateFoodStatus",
            {
              id: id,
              foodStatus: 0
            }).then(res => {//获取返回结果
          this.updateStatus2Success()//下架成功的通知方法
          this.foodData = res.data.data;//更新数据
        })
      })
    },
    //菜品类型
    caipinType(){
      this.dialogFormVisible = true //将弹出层设置为弹出
      this.dialogTitle = '修改菜品信息' //修改弹出层标题
    },
    //打开弹框
    open() {
      this.$alert('<strong>这是 <i>HTML</i> 片段</strong>', 'HTML 片段', {
        dangerouslyUseHTMLString: true
      });
    },
    // 添加成功的通知方法
    saveSuccess() {
      this.$message({
        message: '恭喜你，添加成功！！！',
        type: 'success'
      });
    },
    // 删除成功的通知方法
    deleteSuccess() {
      this.$message({
        message: '删除成功！！！',
        type: 'success'
      });
    },
    // 修改成功的通知方法
    updateSuccess() {
      this.$message({
        message: '恭喜你，修改成功！！！',
        type: 'success'//类型设置为成功样式
      });
    },
    // 商品上架成功的通知方法
    updateStatus1Success() {
      this.$message({
        message: '恭喜你，商品上架！！！',
        type: 'success'//类型设置为成功样式
      });
    },
    // 商品下架成功的通知方法
    updateStatus2Success() {
      this.$message({
        message: '商品已经下架！！！',
        type: 'success'//类型设置为成功样式
      });
    },
    // 删除菜品类型成功的通知方法
    deleteFoodTypeStatus2Success() {
      this.$message({
        message: '已经删除菜品类型！！！',
        type: 'success'//类型设置为成功样式
      });
    },
    //上传图片之后的方法
    fileUploadSuccess(resource) {
      this.form.foodImg = resource.data
      console.log(this.form.foodImg)
    },
    //上传图片之前的方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传菜品图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传菜品图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //删除菜品类型
    //关闭标签的事件
    handleClose(tag) {
      //移除掉那一栏
      this.options.splice(this.options.indexOf(tag.id), 1);
      // alert(tag.id)
      //删除食物类型
      this.$axios.delete("http://localhost:9527/backstagesupporter/deleteFoodTypeById", {
          params: {//发送请求
            id: tag.id
          }
          }).then(res => {//获取返回结果
        this.deleteFoodTypeStatus2Success()//删除菜品类型通知方法
        this.options = res.data.data;//更新数据
      })
    },
    //点击新增标签事件
    showInput() {
      //将文本框设置为真
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //新增标签事件
    //新增菜品类型
    handleInputConfirm() {
      //将文本框的值拿到
      let inputValue = this.inputValue;
      if (inputValue) {
        this.options.push(inputValue);
      }
      //将文本框设置为假
      this.inputVisible = false;
      //清空的文本框的值
      this.inputValue = '';
    },
    //点击tag的事件
    changeValue(tag) {
      //把文本框设置为真
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
      this.inputValue = tag.typeName
      this.tempTag = tag
      this.isChange = true
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  display: block;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
